package Scaner.scan;

import android.content.Context;

import com.scandecode.ScanDecode;
import com.scandecode.inf.ScanInterface;

import android.os.Handler;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

import util.StringUtils;

/**
 * Created by zhengjinglan on 2018/5/26.
 */

public class TimerInfraraedScaner extends Scaner {

    private final String TAG = "scaner";

    private Context context;
    private ScanInterface scanDecode;
    private int scancount = 0;
    final List<String> scanData = new ArrayList<>();

    public TimerInfraraedScaner(Context context) {
        this.context = context;
        init();
        getData();
    }

    @Override
    public void init() {
        //初始化扫描服务
        scanDecode = new ScanDecode(context);
        scanDecode.initService("true");
    }

    @Override
    public void destory() {
        //回复初始状态
        if (scanDecode != null) {
            scanDecode.onDestroy();
        }
    }

    /**
     * 启动单次扫描
     */
    @Override
    public void playSingle() {
        scanDecode.starScan();
    }

    /**
     * 启动多次扫描
     */
    @Override
    public void playRepeat() {
        scancount = 0;
        handler.removeCallbacks(startTask);
        handler.postDelayed(startTask, 0);
    }

    /**
     * 停止扫描
     */
    @Override
    public void stop() {
        scanDecode.stopScan();
        handler.removeCallbacks(startTask);
    }

    @Override
    public List<String> getData() {
        //返回扫描数据
        scanDecode.getBarCode(new ScanInterface.OnScanListener() {

            @Override
            public void getBarcode(String data) {
                scancount += 1;
                String result = StringUtils.replaceBlank(data);
                if (result != null && result.length() > 8) {
                    scanData.add(result.substring(result.length() - 8));
                } else {
                    scanData.add(result);
                }
                if (scanerListener != null) {
                    scanerListener.onScaning(scanData);
                }
            }
        });
        Log.e(TAG, scanData.toString());
        return scanData;
    }

    //连续扫描
    Handler handler = new Handler();
    private Runnable startTask = new Runnable() {
        @Override
        public void run() {
            scanDecode.starScan();
            handler.postDelayed(startTask, 1000);
        }
    };
}
